package at.fhj.itm10.ticketmaster.beans;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.Calendar;
import java.util.Map;

import javax.annotation.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import at.fhj.itm10.ticketmaster.models.Order;

/**
 * @author 	Kevin Reinmueller
 * @since	November 2012
 */

@ManagedBean
@RequestScoped
public class OrderConfirmationBean {

	private String tx = null;
	private FacesContext context;
	private Map<String, String> paramMap;
	
	public OrderConfirmationBean() {
		// get tx GET-URL-parameter
		context = FacesContext.getCurrentInstance();
        paramMap = context.getExternalContext().getRequestParameterMap();
        tx = paramMap.get("tx");
	}

	/**
	 * finalize order
	 * checks if order is payed (with paypal)
	 * writes order in database and empties the cart
	 * @return BOOLEAN
	 */
	public boolean finalizeOrder() {
		Boolean ret = false;
		
		if(tx != null)
			ret = this.checkIfPaid(tx);
		else
			ret = false;
				
		return ret;
	}
	
	/**
	 * checkIfPaid
	 * checks via PayPal PDT if order is correctly paid
	 * @param String tx
	 * @return BOOLEAN
	 */
	private boolean checkIfPaid(String tx) {
		Boolean ret = false;
		URL	url = null;
		URLConnection urlConn = null;
		DataOutputStream cgiInput;
	
		// init trustmanager
		TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {
				public java.security.cert.X509Certificate[] getAcceptedIssuers() {
					return null;
				}
				public void checkClientTrusted(X509Certificate[] certs, String authType) {
				}
				public void checkServerTrusted(X509Certificate[] certs, String authType) {
				}
			}
		};

		// Install the all-trusting trust manager
		SSLContext sc = null;

		try {
			sc = SSLContext.getInstance("SSL");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}

		try {
			sc.init(null, trustAllCerts, new java.security.SecureRandom());
		} catch (KeyManagementException e) {
			e.printStackTrace();
		}

		HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
	
		// Create all-trusting host name verifier
		HostnameVerifier allHostsValid = new HostnameVerifier() {
			public boolean verify(String hostname, SSLSession session) {
				return true;
			}
		};
	
		// Install the all-trusting host verifier
		HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

		// URL of target page script.
		// https://sandbox.paypal.com/cgi-bin/webscr
		try {
			url = new URL("https://sandbox.paypal.com/cgi-bin/webscr");
			urlConn = url.openConnection();
			urlConn.setDoInput(true);
			urlConn.setDoOutput(true);
			urlConn.setUseCaches(false);
			urlConn.setRequestProperty("Content-Type",  "application/x-www-form-urlencoded");

			// Send POST output.
			cgiInput = new DataOutputStream(urlConn.getOutputStream());
	
			String content = "tx=" + URLEncoder.encode(tx, "UTF-8") 
					 + "&cmd=" 
					 + URLEncoder.encode("_notify-synch", "UTF-8")
					 + "&at="
					 + URLEncoder.encode("AZESR62zqA6mFvTErHtScbstjvHybjUaSlrkIFcR64-B48iRXSRFhlmCSXq", "UTF-8");
		
			cgiInput.writeBytes(content);
			cgiInput.flush();
			cgiInput.close();

			// reads the CGI response and print it inside the servlet content
			BufferedReader cgiOutput = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
			cgiOutput.readLine();
			String line = null;
			while (null != (line = cgiOutput.readLine())){
			    String[] splitArr = line.split("=");
			    
			    if(splitArr.length > 1) {
			    	// System.out.println(splitArr[0] + splitArr[1]);
			    	if(splitArr[0].equals("payment_status") && splitArr[1].equals("Completed")) {
			    		ret = true;
			    	}
			    }	
			}
			cgiOutput.close();

			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

			return ret;
		}
}